package com.xmhmyh.generalframework.project.systool.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xmhmyh.generalframework.common.BaseController;
import com.xmhmyh.generalframework.common.entity.DataGridRequest;
import com.xmhmyh.generalframework.common.entity.Response;
import com.xmhmyh.generalframework.common.enums.LogBusType;
import com.xmhmyh.generalframework.common.enums.LogModule;
import com.xmhmyh.generalframework.common.enums.LogSourceType;
import com.xmhmyh.generalframework.common.enums.SortOrder;
import com.xmhmyh.generalframework.framework.aspectj.annotation.Log;
import com.xmhmyh.generalframework.project.systool.conversion.Tabel2TableVOConversion;
import com.xmhmyh.generalframework.project.systool.dto.TableDTO;
import com.xmhmyh.generalframework.project.systool.entity.Table;
import com.xmhmyh.generalframework.project.systool.mapper.TableMapper;
import com.xmhmyh.generalframework.project.systool.service.ITableService;
import com.xmhmyh.generalframework.project.systool.vo.TableVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author
 * @since
 */
@Api(tags = "生成表接口")
@RestController
@RequestMapping("/gen/table")
public class TableController extends BaseController {

    @Resource
    private TableMapper tableMapper;
    @Autowired
    private ITableService tableService;

    @PreAuthorize("hasAuthority('systool:gencode:import')")
    @ApiOperation(value = "获取导入列表")
    @PostMapping("getImportList")
    public Response getImportListHandler(String tableName) {
        List<Table> tableList = tableMapper.selectDbTableList(tableName);
        return Response.success(tableList);
    }

    @Log(busType = LogBusType.IMPORT, source = LogSourceType.MANAGE, module = LogModule.CODE_GEN)
    @PreAuthorize("hasAuthority('systool:gencode:import')")
    @ApiOperation(value = "导入表")
    @PostMapping("importTable")
    public Response importTableHandler(@RequestBody List<TableDTO> tableNameList) {
        tableService.importTableHandler(getLoginUser().getUser(), tableNameList);
        return Response.success();
    }

    @PreAuthorize("hasAuthority('systool:gencode:list')")
    @ApiOperation(value = "查找导入列表")
    @PostMapping("pagination")
    public Response paginationHandler(@RequestBody DataGridRequest params) {
        params = addAccountConstraints(params);
        params.setSortOrder(SortOrder.DESC.getLabel());
        params.setSortName("createTime");
        IPage<Table> tableIPage = tableService.paginate(params);
        IPage<TableVO> tableVOIPage = Tabel2TableVOConversion.conversion(tableIPage);
        return Response.success(tableVOIPage);
    }

    /**
     * 预览代码
     */
    @ApiOperation(value = "预览代码")
    @PreAuthorize("hasAuthority('systool:gencode:preview')")
    @PostMapping("preview")
    public Response preview(Long tableId) throws IOException {
        Map<String, String> dataMap = tableService.previewCode(tableId);
        return Response.success(dataMap);
    }


    @Log(busType = LogBusType.GEN, source = LogSourceType.MANAGE, module = LogModule.CODE_GEN)
    @PreAuthorize("hasAuthority('systool:gencode:gen')")
    @ApiOperation(value = "生成代码")
    @GetMapping("gen/{tableId}")
    public void genHandler(HttpServletResponse response, @PathVariable(value = "tableId") Long tableId) throws IOException {
        byte[] data = tableService.genHandler(tableId);
        genCode(response, data);
    }

    @Log(busType = LogBusType.DELETE, source = LogSourceType.MANAGE, module = LogModule.CODE_GEN)
    @PreAuthorize("hasAuthority('systool:gencode:del')")
    @ApiOperation(value = "删除代码")
    @PostMapping("del")
    public Response delHandler(Long tableId) throws IOException {
        tableService.delHandler(tableId);
        return Response.success();
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"genCode.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
